<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优品购 - 库存商品展示</title>
    <!-- 引入Tailwind CSS（无需本地安装） -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind自定义配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',    // 主色（蓝色）
                        success: '#10B981',    // 成功色（绿色，库存充足）
                        warning: '#F59E0B',    // 警告色（黄色，库存紧张）
                        danger: '#EF4444',     // 危险色（红色，库存不足）
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
</head>
<body class="font-inter bg-gray-50 text-gray-800">
    <!-- 导航栏 -->
    <header class="fixed top-0 left-0 w-full bg-white shadow-sm z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-shopping-bag text-2xl text-primary"></i>
                <span class="text-xl font-bold text-primary">优品购</span>
            </div>
            <!-- 搜索框 -->
            <div class="w-1/3">
                <div class="relative">
                    <input id="searchInput" type="text" placeholder="搜索商品..." 
                           class="w-full py-2 px-4 pr-10 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <button id="searchBtn" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-primary">
                        <i class="fa fa-search"></i>
                    </button>
                </div>
            </div>
            <!-- 购物车按钮 -->
            <button id="cartBtn" class="relative p-2 rounded-full hover:bg-gray-100 transition-colors">
                <i class="fa fa-shopping-cart text-xl"></i>
                <span id="cartCount" class="absolute -top-1 -right-1 bg-primary text-white text-xs w-5 h-5 flex items-center justify-center rounded-full">0</span>
            </button>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-24 pb-16">
        <!-- 分类筛选栏 -->
        <div class="mb-8 flex flex-wrap gap-2">
            <button class="category-btn px-4 py-2 bg-primary text-white rounded-full text-sm font-medium" data-id="">
                全部商品
            </button>
            <!-- 分类通过JS动态加载 -->
        </div>

        <!-- 排序与数量 -->
        <div class="mb-6 flex justify-between items-center">
            <span id="productCountText" class="text-gray-600">共 0 件商品</span>
            <div class="relative">
                <select id="sortSelect" class="appearance-none bg-white border border-gray-300 rounded-lg py-2 pl-3 pr-8 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <option value="default">默认排序（最新上架）</option>
                    <option value="price-asc">价格从低到高</option>
                    <option value="price-desc">价格从高到低</option>
                    <option value="rating">评分从高到低</option>
                </select>
                <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none"></i>
            </div>
        </div>

        <!-- 商品网格（核心：展示库存） -->
        <div id="productGrid" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            <!-- 商品卡片通过JS动态加载 -->
            <div id="loading" class="col-span-full flex justify-center items-center py-16">
                <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
            </div>
            <div id="noProduct" class="col-span-full hidden flex justify-center items-center py-16 text-gray-500">
                <div class="text-center">
                    <i class="fa fa-search text-5xl mb-4"></i>
                    <p>未找到符合条件的商品</p>
                </div>
            </div>
        </div>

        <!-- 分页 -->
        <div id="pagination" class="mt-10 flex justify-center items-center gap-2 hidden">
            <button id="prevPage" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <i class="fa fa-chevron-left"></i>
            </button>
            <span id="pageInfo" class="px-4 py-2">第 1 页 / 共 0 页</span>
            <button id="nextPage" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <i class="fa fa-chevron-right"></i>
            </button>
        </div>
    </main>

    <!-- 购物车侧边栏 -->
    <div id="cartSidebar" class="fixed top-0 right-0 h-full w-full md:w-96 bg-white shadow-2xl z-50 transform translate-x-full transition-transform duration-300 ease-in-out">
        <div class="h-full flex flex-col">
            <!-- 侧边栏头部 -->
            <div class="p-4 border-b flex justify-between items-center">
                <h2 class="text-xl font-bold">我的购物车</h2>
                <button id="closeCart" class="p-2 hover:bg-gray-100 rounded-full">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <!-- 购物车内容 -->
            <div id="cartContent" class="flex-1 overflow-y-auto p-4">
                <!-- 空购物车 -->
                <div id="emptyCart" class="h-full flex flex-col items-center justify-center text-center text-gray-500">
                    <i class="fa fa-shopping-cart text-5xl mb-4"></i>
                    <p class="mb-2">购物车还是空的</p>
                    <p class="text-sm mb-6">快去添加喜欢的商品吧～</p>
                    <button id="goShopping" class="px-4 py-2 bg-primary text-white rounded-full text-sm font-medium">
                        开始购物
                    </button>
                </div>
                <!-- 购物车商品（JS动态加载） -->
                <div id="cartItems" class="space-y-4 hidden"></div>
            </div>
            <!-- 购物车底部（总价与结算） -->
            <div id="cartFooter" class="p-4 border-t hidden">
                <div class="flex justify-between mb-4">
                    <span class="text-gray-600">合计：</span>
                    <span id="cartTotal" class="text-xl font-bold text-primary">¥0.00</span>
                </div>
                <button id="checkoutBtn" class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90">
                    去结算
                </button>
            </div>
        </div>
    </div>

    <!-- 遮罩层 -->
    <div id="overlay" class="fixed inset-0 bg-black/50 z-40 opacity-0 pointer-events-none transition-opacity duration-300"></div>

    <!-- 提示弹窗 -->
    <div id="toast" class="fixed bottom-6 left-1/2 -translate-x-1/2 bg-gray-800 text-white px-6 py-3 rounded-lg shadow-lg z-50 opacity-0 translate-y-10 transition-all duration-300">
        <span id="toastText">操作成功</span>
    </div>

    <script>
        // -------------------------- 全局配置 --------------------------
        const API_BASE_URL = "http://localhost:5000/api";  // 后端API地址（与Flask启动地址一致）
        let sessionId = localStorage.getItem('shopping_session_id');
        // 生成会话ID（无登录状态下标识用户）
        if (!sessionId) {
            sessionId = `session_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
            localStorage.setItem('shopping_session_id', sessionId);
        }

        // -------------------------- 全局状态 --------------------------
        let currentPage = 1;
        let totalPages = 0;
        let totalProducts = 0;
        let currentCategory = '';  // 当前选中分类（空为全部）
        let currentSearch = '';    // 当前搜索关键词
        let currentSort = 'default';  // 当前排序方式

        // -------------------------- DOM元素 --------------------------
        const productGrid = document.getElementById('productGrid');
        const loading = document.getElementById('loading');
        const noProduct = document.getElementById('noProduct');
        const pagination = document.getElementById('pagination');
        const pageInfo = document.getElementById('pageInfo');
        const prevPageBtn = document.getElementById('prevPage');
        const nextPageBtn = document.getElementById('nextPage');
        const productCountText = document.getElementById('productCountText');
        const sortSelect = document.getElementById('sortSelect');
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const cartBtn = document.getElementById('cartBtn');
        const cartSidebar = document.getElementById('cartSidebar');
        const closeCart = document.getElementById('closeCart');
        const overlay = document.getElementById('overlay');
        const emptyCart = document.getElementById('emptyCart');
        const cartItems = document.getElementById('cartItems');
        const cartFooter = document.getElementById('cartFooter');
        const cartTotal = document.getElementById('cartTotal');
        const cartCount = document.getElementById('cartCount');
        const goShopping = document.getElementById('goShopping');
        const checkoutBtn = document.getElementById('checkoutBtn');
        const toast = document.getElementById('toast');
        const toastText = document.getElementById('toastText');

        // -------------------------- 工具函数 --------------------------
        // 显示提示
        function showToast(text, isError = false) {
            toastText.textContent = text;
            toast.classList.remove('opacity-0', 'translate-y-10');
            toast.classList.add('opacity-100', 'translate-y-0');
            if (isError) {
                toast.classList.remove('bg-gray-800');
                toast.classList.add('bg-danger');
            } else {
                toast.classList.remove('bg-danger');
                toast.classList.add('bg-gray-800');
            }
            setTimeout(() => {
                toast.classList.remove('opacity-100', 'translate-y-0');
                toast.classList.add('opacity-0', 'translate-y-10');
            }, 2000);
        }

        // 格式化价格
        function formatPrice(price) {
            return `¥${parseFloat(price).toFixed(2)}`;
        }

        // -------------------------- 商品加载与展示 --------------------------
        // 加载分类
        async function loadCategories() {
            try {
                const res = await fetch(`${API_BASE_URL}/categories`);
                if (!res.ok) throw new Error('分类加载失败');
                const categories = await res.json();
                const categoryContainer = document.querySelector('.flex.flex-wrap.gap-2');
                
                // 添加分类按钮
                categories.forEach(cat => {
                    const btn = document.createElement('button');
                    btn.className = 'category-btn px-4 py-2 bg-white text-gray-700 rounded-full text-sm font-medium hover:bg-gray-100';
                    btn.textContent = cat.name;
                    btn.setAttribute('data-id', cat.id);
                    btn.addEventListener('click', () => {
                        // 切换分类选中状态
                        document.querySelectorAll('.category-btn').forEach(b => {
                            b.classList.remove('bg-primary', 'text-white');
                            b.classList.add('bg-white', 'text-gray-700');
                        });
                        btn.classList.remove('bg-white', 'text-gray-700');
                        btn.classList.add('bg-primary', 'text-white');
                        // 更新当前分类并重新加载商品
                        currentCategory = cat.id;
                        currentPage = 1;
                        loadProducts();
                    });
                    categoryContainer.appendChild(btn);
                });
            } catch (err) {
                showToast('分类加载失败，请刷新重试', true);
                console.error(err);
            }
        }

        // 加载商品（核心：展示库存）
        async function loadProducts() {
            // 显示加载状态
            loading.classList.remove('hidden');
            noProduct.classList.add('hidden');
            pagination.classList.add('hidden');
            productGrid.querySelectorAll('.product-card').forEach(card => card.remove());

            try {
                // 构建请求参数
                const params = new URLSearchParams();
                params.append('page', currentPage);
                params.append('per_page', 8);
                if (currentCategory) params.append('category', currentCategory);
                if (currentSearch) params.append('search', currentSearch);
                if (currentSort) params.append('sort', currentSort);

                const res = await fetch(`${API_BASE_URL}/products?${params.toString()}`);
                if (!res.ok) throw new Error('商品加载失败');
                const data = await res.json();
                
                totalProducts = data.total;
                totalPages = data.pages;
                const products = data.products;

                // 隐藏加载状态
                loading.classList.add('hidden');

                // 更新商品数量文本
                productCountText.textContent = `共 ${totalProducts} 件商品`;

                // 处理无商品情况
                if (products.length === 0) {
                    noProduct.classList.remove('hidden');
                    return;
                }

                // 显示分页
                pagination.classList.remove('hidden');
                pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
                prevPageBtn.disabled = currentPage === 1;
                nextPageBtn.disabled = currentPage === totalPages;

                // 渲染商品卡片（突出库存状态）
                products.forEach(prod => {
                    const card = document.createElement('div');
                    card.className = 'product-card bg-white rounded-xl overflow-hidden shadow hover:shadow-lg transition-shadow';
                    
                    // 库存状态样式（充足/紧张/不足）
                    let stockClass = 'text-success';
                    let stockText = `库存充足（${prod.stock}件）`;
                    if (prod.stock < 10) {
                        stockClass = 'text-warning';
                        stockText = `库存紧张（仅剩${prod.stock}件）`;
                    }
                    if (prod.stock === 0) {
                        stockClass = 'text-danger';
                        stockText = '已售罄';
                    }

                    // 商品卡片HTML（含库存展示）
                    card.innerHTML = `
                        <div class="relative">
                            <img src="${prod.image_url}" alt="${prod.name}" class="w-full h-48 object-cover">
                            <span class="absolute top-2 left-2 ${stockClass} text-xs font-bold px-2 py-1 rounded bg-white/80 backdrop-blur-sm">
                                ${stockText}
                            </span>
                        </div>
                        <div class="p-4">
                            <h3 class="font-medium text-lg mb-2 line-clamp-1">${prod.name}</h3>
                            <p class="text-gray-500 text-sm mb-3 line-clamp-2">${prod.description || '暂无描述'}</p>
                            <div class="flex items-center text-yellow-400 text-xs mb-3">
                                ${Array(Math.floor(prod.rating)).fill('<i class="fa fa-star"></i>').join('')}
                                ${prod.rating % 1 >= 0.5 ? '<i class="fa fa-star-half-o"></i>' : ''}
                                ${Array(5 - Math.ceil(prod.rating)).fill('<i class="fa fa-star-o"></i>').join('')}
                                <span class="text-gray-500 ml-1">(${prod.review_count}评价)</span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-primary font-bold text-xl">${formatPrice(prod.price)}</span>
                                <button class="add-to-cart p-2 bg-primary/10 text-primary rounded-full hover:bg-primary hover:text-white transition-colors ${prod.stock === 0 ? 'opacity-50 cursor-not-allowed' : ''}"
                                        data-id="${prod.id}" data-name="${prod.name}" data-stock="${prod.stock}">
                                    <i class="fa fa-shopping-cart"></i>
                                </button>
                            </div>
                        </div>
                    `;
                    productGrid.appendChild(card);

                    // 添加购物车按钮事件
                    const addBtn = card.querySelector('.add-to-cart');
                    if (prod.stock > 0) {
                        addBtn.addEventListener('click', () => {
                            addToCart(prod.id, 1);
                        });
                    }
                });
            } catch (err) {
                loading.classList.add('hidden');
                noProduct.classList.remove('hidden');
                noProduct.querySelector('p').textContent = '商品加载失败，请刷新重试';
                showToast('商品加载失败', true);
                console.error(err);
            }
        }

        // -------------------------- 购物车操作 --------------------------
        // 加载购物车
        async function loadCart() {
            try {
                const res = await fetch(`${API_BASE_URL}/cart?session_id=${sessionId}`);
                if (!res.ok) throw new Error('购物车加载失败');
                const data = await res.json();
                
                const cartItemList = data.items;
                const totalItems = data.total_items;
                const totalPrice = data.total_price;

                // 更新购物车数量徽章
                cartCount.textContent = totalItems;

                // 处理空购物车
                if (cartItemList.length === 0) {
                    emptyCart.classList.remove('hidden');
                    cartItems.classList.add('hidden');
                    cartFooter.classList.add('hidden');
                    return;
                }

                // 显示购物车商品和底部
                emptyCart.classList.add('hidden');
                cartItems.classList.remove('hidden');
                cartFooter.classList.remove('hidden');

                // 更新购物车总价
                cartTotal.textContent = formatPrice(totalPrice);

                // 清空现有购物车商品
                cartItems.innerHTML = '';

                // 渲染购物车商品（含实时库存）
                cartItemList.forEach(item => {
                    const cartItem = document.createElement('div');
                    cartItem.className = 'flex items-center gap-3 pb-3 border-b';
                    
                    // 库存状态提示
                    let stockTip = '';
                    if (item.product.stock < item.quantity) {
                        stockTip = `<p class="text-danger text-xs mt-1">库存不足！当前仅${item.product.stock}件</p>`;
                    }

                    cartItem.innerHTML = `
                        <img src="${item.product.image_url}" alt="${item.product.name}" class="w-16 h-16 object-cover rounded">
                        <div class="flex-1 min-w-0">
                            <h4 class="font-medium line-clamp-1">${item.product.name}</h4>
                            <p class="text-primary font-medium">${formatPrice(item.product.price)}</p>
                            <div class="flex items-center mt-2">
                                <button class="decrease-btn w-6 h-6 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100" data-id="${item.id}">
                                    <i class="fa fa-minus text-xs"></i>
                                </button>
                                <span class="mx-2 text-gray-800">${item.quantity}</span>
                                <button class="increase-btn w-6 h-6 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100" data-id="${item.id}" data-stock="${item.product.stock}">
                                    <i class="fa fa-plus text-xs"></i>
                                </button>
                            </div>
                            ${stockTip}
                        </div>
                        <button class="delete-btn text-gray-400 hover:text-danger" data-id="${item.id}">
                            <i class="fa fa-trash"></i>
                        </button>
                    `;
                    cartItems.appendChild(cartItem);

                    // 绑定购物车操作事件
                    cartItem.querySelector('.decrease-btn').addEventListener('click', (e) => {
                        updateCartItem(e.currentTarget.dataset.id, item.quantity - 1);
                    });
                    cartItem.querySelector('.increase-btn').addEventListener('click', (e) => {
                        const maxStock = parseInt(e.currentTarget.dataset.stock);
                        if (item.quantity >= maxStock) {
                            showToast('库存不足，无法增加数量', true);
                            return;
                        }
                        updateCartItem(e.currentTarget.dataset.id, item.quantity + 1);
                    });
                    cartItem.querySelector('.delete-btn').addEventListener('click', (e) => {
                        deleteCartItem(e.currentTarget.dataset.id);
                    });
                });
            } catch (err) {
                showToast('购物车加载失败，请刷新重试', true);
                console.error(err);
            }
        }

        // 添加商品到购物车
        async function addToCart(productId, quantity) {
            try {
                const res = await fetch(`${API_BASE_URL}/cart/items`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: sessionId,
                        product_id: productId,
                        quantity: quantity
                    })
                });

                const data = await res.json();
                if (!res.ok) throw new Error(data.error || '添加失败');

                // 重新加载购物车
                loadCart();
                showToast('商品已添加到购物车');
            } catch (err) {
                showToast(err.message, true);
                console.error(err);
            }
        }

        // 更新购物车商品数量
        async function updateCartItem(itemId, newQuantity) {
            try {
                const res = await fetch(`${API_BASE_URL}/cart/items/${itemId}?session_id=${sessionId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ quantity: newQuantity })
                });

                const data = await res.json();
                if (!res.ok) throw new Error(data.error || '更新失败');

                // 重新加载购物车
                loadCart();
            } catch (err) {
                showToast(err.message, true);
                console.error(err);
            }
        }

        // 删除购物车商品
        async function deleteCartItem(itemId) {
            try {
                const res = await fetch(`${API_BASE_URL}/cart/items/${itemId}?session_id=${sessionId}`, {
                    method: 'DELETE'
                });

                if (!res.ok) throw new Error('删除失败');

                // 重新加载购物车
                loadCart();
                showToast('商品已从购物车删除');
            } catch (err) {
                showToast('删除失败，请重试', true);
                console.error(err);
            }
        }

        // -------------------------- 事件绑定 --------------------------
        // 排序变化
        sortSelect.addEventListener('change', () => {
            currentSort = sortSelect.value;
            currentPage = 1;
            loadProducts();
        });

        // 搜索
        searchBtn.addEventListener('click', () => {
            currentSearch = searchInput.value.trim();
            currentPage = 1;
            loadProducts();
        });
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') searchBtn.click();
        });

        // 分页
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                loadProducts();
            }
        });
        nextPageBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                loadProducts();
            }
        });

        // 购物车侧边栏
        cartBtn.addEventListener('click', () => {
            cartSidebar.classList.remove('translate-x-full');
            overlay.classList.remove('opacity-0', 'pointer-events-none');
            document.body.style.overflow = 'hidden';
            // 加载购物车数据
            loadCart();
        });
        closeCart.addEventListener('click', () => {
            cartSidebar.classList.add('translate-x-full');
            overlay.classList.add('opacity-0', 'pointer-events-none');
            document.body.style.overflow = '';
        });
        overlay.addEventListener('click', () => {
            closeCart.click();
        });
        goShopping.addEventListener('click', () => {
            closeCart.click();
        });
        checkoutBtn.addEventListener('click', () => {
            showToast('结算功能待开发');
        });

        // -------------------------- 初始化 --------------------------
        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', () => {
            loadCategories();  // 加载分类
            loadProducts();    // 加载商品
        });
    </script>
</body>
</html>